<script setup>
  import { ref, watch } from 'vue'
  import { addStudentPlanService, addPlanTaskService, addplanService, updateplanService, addtaskService, updateTaskService, removefileService } from '@/api/plan'
  import { upLoadfiles, addAttachments } from '@/api/upload'
  import { updateGoalService } from '@/api/user'
  import { Plus } from '@element-plus/icons-vue'
  import {baseURL} from '@/utils/request'
  const DrawerVisible = ref(false)
  const images = ref([])
  const tasks = ref([])
  const filtertasks=ref([])
  const nulltasks = [{
    order: 2,
    type: '校内实践',
    content: '',
    attachments: []
  }, {
    order: 3,
    type: '校外实践',
    content: '',
    attachments: []
  }, {
    order: 4,
    type: '国际交流',
    content: '',
    attachments: []
  }, {
    order: 5,
    type: '其他',
    content: '',
    attachments: []
  }]

  const formModel = ref({})
  const open = async (row) => {
    DrawerVisible.value = true
    formModel.value = { ...row }
    tasks.value=[]
    scores.value = []
  }

  defineExpose({
    open
  })
  const options = [
    {
      value: '报到前',
      label: '报到前',
    },
    {
      value: '第一学期',
      label: '第一学期',
    },
    {
      value: '大一寒假',
      label: '大一寒假',
    },
    {
      value: '第二学期',
      label: '第二学期',
    },
    {
      value: '大一暑假',
      label: '大一暑假',
    },
    {
      value: '第三学期',
      label: '第三学期',
    },
    {
      value: '大二寒假',
      label: '大二寒假',
    },
    {
      value: '第四学期',
      label: '第四学期',
    },
    {
      value: '大二暑假',
      label: '大二暑假',
    },
    {
      value: '第五学期',
      label: '第五学期',
    },
    {
      value: '大三寒假',
      label: '大三寒假',
    },
    {
      value: '第六学期',
      label: '第六学期',
    },
    {
      value: '大三暑假',
      label: '大三暑假',
    },
    {
      value: '第七学期',
      label: '第七学期',
    },
    {
      value: '大四寒假',
      label: '大四寒假',
    },
    {
      value: '第八学期',
      label: '第八学期',
    },
    {
      value: '毕业后',
      label: '毕业后',
    }
  ]
  const selectPlan = ref([])
  const scores = ref([])

  const PlanChange = () => {
    scores.value = []
    const courses = ref([])
    //查找该学期tasks和goal
    formModel.value.stage = ''
    selectPlan.value = formModel.value.plans.find(item => item.term == formModel.value.term)
    tasks.value = selectPlan.value && selectPlan.value.tasks.length > 0 ? selectPlan.value.tasks : nulltasks
    formModel.value.stage = selectPlan.value ? selectPlan.value.stage : ''
    //查找该学期课程
    if (selectPlan.value) {
      scores.value = selectPlan.value.scores
    } else {
      courses.value = formModel.value.klass.courses.filter(item => item.term == formModel.value.term)
      courses.value.forEach(course => {
        scores.value.push({ course })
      })
    }
  if(tasks.value.length>0){
    filtertasks.value[0]=tasks.value.filter(item=>item.order==2)
    filtertasks.value[1]=tasks.value.filter(item=>item.order==3)
    filtertasks.value[2]=tasks.value.filter(item=>item.order==4)
    filtertasks.value[3]=tasks.value.filter(item=>item.order==5)
  }
  }



  const onSubmit = async () => {
    const attachments = []

    // for (const task of tasks.value) {
    //   let formData = new FormData();
    //   const new_attachments = [];

    //   for (const file of task.attachments) {
    //     if (file._id) {
    //       new_attachments.push(file);
    //     } else {
    //       formData.append('file', file.raw)
    //     }

    //   }
    //   const res = await upLoadfiles(formData)
    //   if (res.data) {
    //     for (const path of res.data.paths) {
    //       const attachment = {
    //         origin: path.origin,
    //         name: path.origin.substring(0, path.origin.lastIndexOf(".")),
    //         date: new Date(),
    //         auto: path.auto,
    //         ext: path.ext,
    //         size: '0KB'
    //       }
    //       if (path.size / 1024 < 1024) {
    //         attachment.size = (path.size / 1024).toFixed(1) + "KB";
    //       } else if (path.size / (1024 * 1024) < 1024) {
    //         attachment.size = (path.size / (1024 * 1024)).toFixed(1) + "MB";
    //       } else {
    //         attachment.size = (path.size / (1024 * 1024 * 1024)).toFixed(1) + "GB";
    //       }
    //       const res = await addAttachments({ attachment: attachment })
    //       new_attachments.push(res.data.attachment);

    //     }

    //   }
    //   attachments.push(new_attachments)

    // }
    //课堂
    
    //const finaltasks = Array.from(tasks.value)
    const finaltasks =[]
    filtertasks.value.forEach(item=>{
    item.forEach(e=>{
      finaltasks.push(e)
    })
    })
    console.log(finaltasks)
    // finaltasks.forEach((item, index) => {
    //   item.attachments = attachments[index]
    // })


    const createdPlan = ref([])
    const createdTask = ref([])
    //更新学生goal
    await updateGoalService({
      id: formModel.value._id,
      goal: formModel.value.goal
    })


    if (selectPlan.value) {
      //更新计划
      await updateplanService({
        id: selectPlan.value._id,
        plan: {
          term: formModel.value.term,
          stage: formModel.value.stage,
          scores: scores.value
        }
      })
      ElMessage.success('计划已更新')
    } else {
      //若该学期创建计划
      const planres = await addplanService({

        plan: {
          term: formModel.value.term,
          stage: formModel.value.stage,
          scores: scores.value
        }
      })
      createdPlan.value = planres.data.plan
      //更新学生外键和总目标
      await addStudentPlanService({
        id: formModel.value._id,
        plan: createdPlan.value,

      })

      ElMessage.success('计划已创建')
    }

    //若有则更新
    if (selectPlan.value.tasks.length>0) {
      // for (const task of selectPlan.value.tasks) {
      //   for (const a of task.attachments) {
      //     await removefileService(a._id)
      //   }
      // }
      for (const task of finaltasks) {
        await updateTaskService({
          id: task._id,
          task: task
        })
      }
      ElMessage.success('课堂已更新')
    } else {
      //若没有则创建新课堂
      const taskres = await addtaskService({
        id: formModel.value._id,
        term: formModel.value.term,
        tasks: finaltasks
      })
      createdTask.value = taskres.data

      if (taskres.data.code == 201) {
        //更新plan外键
        await addPlanTaskService({
          tasks: createdTask.value.tasks,
          id: createdTask.value.plan_id
        })
      }

      ElMessage.success(taskres.data.msg)
    }

    DrawerVisible.value = false


  }
//  const handlePreview=(file)=>{
//   console.log(file)
//   if(file.raw){
//     window.open(file.url)
//   }else{
//     window.open(baseURL+'/files/'+file.auto)
//   }
  
//   }
//   const upLoadFile = (file, filelist) => {
//     tasks.value[0].attachments = filelist
//   }

//   const fileRemove = (file, filelist) => {
//     tasks.value[0].attachments = filelist
//   }

 
//   const upLoadFile1 = (file, filelist) => {
//     tasks.value[1].attachments = filelist
//   }
//   const fileRemove1 = (file, filelist) => {
//     tasks.value[1].attachments = filelist
//   }

//   const upLoadFile2 = (file, filelist) => {
//     tasks.value[2].attachments = filelist

//   }
//   const fileRemove2 = (file, filelist) => {
//     tasks.value[2].attachments = filelist
//   }

//   const upLoadFile3 = (file, filelist) => {
//     tasks.value[3].attachments = filelist
//   }
//   const fileRemove3 = (file, filelist) => {
//     tasks.value[3].attachments = filelist
//   }

</script>
<template>
  <el-drawer v-model="DrawerVisible" title="编辑计划" direction="rtl" size="50%">

    <el-form label-width="150px" :model="formModel">
      <el-form-item label="学号">
        <el-input v-model="formModel.code" placeholder="请输入学号" disabled></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="formModel.name" placeholder="请输入姓名" disabled></el-input>
      </el-form-item>
      <el-form-item label="总目标">
        <el-input v-model="formModel.goal" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" placeholder="四年总目标" />
      </el-form-item>

      <el-form-item label="计划">
        <el-select v-model="formModel.term" class="m-2" placeholder="请选择学期" @change="PlanChange"
          style="width: 240px;margin-bottom: 20px;">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="formModel.stage" :autosize="{ minRows: 4, maxRows: 7 }" type="textarea" placeholder="阶段目标" />
      </el-form-item>
      <el-form-item v-if="scores.length>0" label="第一课堂">
        <el-form-item v-for="item in scores">
          <el-input v-model="item.course.name" style="width: 250px;margin-bottom: 10px;" disabled></el-input>
          <el-input v-model="item.target" style="width: 80px;margin-left: 20px;margin-bottom: 10px;" placeholder="理想分数">
          </el-input>
          <el-input v-model="item.final" style="width: 80px;margin-left: 20px;margin-bottom: 10px;" placeholder="实际分数">
          </el-input>
        </el-form-item>
      </el-form-item>
      <el-form-item v-if="scores.length==0&&formModel.term" label="第一课堂">
        <span>该学期未选择课程！</span>
      </el-form-item>
      <el-form-item label="第二课堂" v-if="tasks.length>0" >
        
          <el-input v-for="item in filtertasks[0]" v-model="item.content" :autosize="{ minRows: 4, maxRows:7 }" type="textarea" placeholder="请输入"
          style="margin-bottom: 20px;"></el-input>
      
        
        <!-- <el-upload action class="upload-demo" :file-list="tasks[0].attachments" :on-change="upLoadFile" :on-preview="handlePreview"
          :on-remove="fileRemove" :auto-upload="false">
          <template #trigger>
            <el-button type="warning" text bg>选择文件</el-button>
          </template>
          <template #tip>
            <span class="el-upload__tip">
              文件大小不超过5mb
            </span>
          </template>
        </el-upload> -->
      </el-form-item>
      <el-form-item label="第三课堂" v-if="tasks.length>0">
          <el-input  v-for="item in filtertasks[1]" v-model="item.content" :autosize="{ minRows: 4, maxRows:7 }" type="textarea" placeholder="请输入"style="margin-bottom: 20px;"></el-input>
        <!-- <el-upload action class="upload-demo" :file-list="tasks[1].attachments" :on-change="upLoadFile1" :on-preview="handlePreview"
          :on-remove="fileRemove1" :auto-upload="false">
          <template #trigger>
            <el-button type="warning" text bg>选择文件</el-button>
          </template>
          <template #tip>
            <span class="el-upload__tip">
              文件大小不超过5mb
            </span>
          </template>
        </el-upload> -->
      </el-form-item>
      <el-form-item label="第四课堂" v-if="tasks.length>0">
          <el-input  v-for="item in filtertasks[2]" v-model="item.content" :autosize="{ minRows: 4, maxRows:7 }" type="textarea" placeholder="请输入"
            style="margin-bottom: 20px;"></el-input>
        <!-- <el-upload action class="upload-demo" :file-list="tasks[2].attachments" :on-change="upLoadFile2" :on-preview="handlePreview"
          :on-remove="fileRemove2" :auto-upload="false">
          <template #trigger>
            <el-button type="warning" text bg>选择文件</el-button>
          </template>
          <template #tip>
            <span class="el-upload__tip">
              文件大小不超过5mb
            </span>
          </template>
        </el-upload> -->
      </el-form-item>
      <el-form-item label="其他课堂" v-if="tasks.length>0">
          <el-input v-for="item in filtertasks[3]" v-model="item.content" :autosize="{ minRows: 4, maxRows:7 }" type="textarea" placeholder="请输入"
            style="margin-bottom: 20px;"></el-input>
        <!-- <el-upload action class="upload-demo" :file-list="tasks[3].attachments" :on-change="upLoadFile3" :on-preview="handlePreview"
          :on-remove="fileRemove3" :auto-upload="false">
          <template #trigger>
            <el-button type="warning" text bg>选择文件</el-button>
          </template>
          <template #tip>
            <span class="el-upload__tip">
              文件大小不超过5mb
            </span>
          </template>
        </el-upload> -->
      </el-form-item>
      <el-form-item>
        <el-button @click="onSubmit" type="primary">提交</el-button>
        <el-button @click="DrawerVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
  .avatar-uploader {
    :deep() {
      .avatar {
        width: 178px;
        height: 178px;
        display: inline-block;
      }

      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }

      .el-upload:hover {
        border-color: var(--el-color-primary);

      }

      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }

    }
  }
</style>